package com.dawnling.androidutils.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.dawnling.androidutils.R;

import static android.view.KeyEvent.KEYCODE_BACK;

public class WebviewActivity extends AppCompatActivity {

    private WebView mWebview;
    private String url = "https://s2-test.keytop.cn/msfront/Index";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        mWebview = findViewById(R.id.webview);
        mWebview.loadUrl(url);
        syncCookie(url, "2amug6jfdgiogyth47ewt5n1lobtg58aw32fi5da16adhpnjaeuvescdoh9o50yngckjw94ba2vx1eyd4y0o2br");
        //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
    }

    /**
     * 将cookie同步到WebView
     *
     * @param url                WebView要加载的url
     * @param ManagerTokenCookie 要同步的cookie里的值(根据后台需求取,这里只是列出)
     * @return true 同步cookie成功，false同步cookie失败
     */
    public boolean syncCookie(String url, String ManagerTokenCookie) {
        CookieManager mCookieManager = CookieManager.getInstance();
        mCookieManager.setAcceptCookie(true);
        mCookieManager.setCookie(url, "token=" + ManagerTokenCookie);//以"key=value"形式作为cookie即可
        String newCookie = mCookieManager.getCookie(url);
        //在API 21之后，WebView实现了自动同步Cookie，不需要手动同步，所以，使用时可以添加版本判断；
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(this).sync();
        }
        return TextUtils.isEmpty(newCookie) ? false : true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && mWebview.canGoBack()) {
            mWebview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
